package com.shuai.utils.hander.securityHander;

import com.alibaba.fastjson.JSON;
import com.shuai.model.loginInfo.LoginUserInfo;
import com.shuai.model.loginInfo.UserDetailInfo;
import com.shuai.profile.JwtProfile;
import com.shuai.utils.jwt.JwtUtils;
import com.shuai.utils.redis.RedisUtil;
import com.shuai.utils.returnVo.ReturnModel;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功的认证处理器
 *
 * @author shuai
 * @since 2022
 */
@Slf4j
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private JwtUtils jwtUtils;

    @Resource
    private JwtProfile jwtProfile;

    @Resource
    private RedisUtil redisUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException{
        //获取当前用户信息
        UserDetailInfo userDetailInfo = (UserDetailInfo) authentication.getPrincipal();
        //生成Token
        String token = jwtUtils.generateToken(userDetailInfo);
        //获取生成的token的过期时间
        Long expireTime =  Jwts.parser()
                .setSigningKey(jwtProfile.getSecret())
                .parseClaimsJws(token)
                .getBody().getExpiration().getTime();
        //封装返回的登录信息
        LoginUserInfo userInfo = LoginUserInfo.builder()
                .id(userDetailInfo.getId())
                .username(userDetailInfo.getUsername())
                .token(token)
                .expireTime(expireTime)
                .build();
        //设置返回数据的字符集
        response.setContentType("application/json;charset=utf-8");
        //设置返回的数据
        response.getWriter().write(JSON.toJSONString(ReturnModel.successInstance(userInfo)));
        //把生成的token存到redis
        String tokenKey = "token_"+token;
        redisUtil.set(tokenKey,token,jwtProfile.getExpiration() / 1000);
    }
}
